﻿/*----------------------------------------------------------------------------------------
*
*  Copyright 2019, Gao Hai Hui, <fromzeropoint@126.com>.  All rights reserved.
*  https://gitee.com/helloworldghh/xoskit.git
*  Use of this source code is governed by a MIT license
*  that can be found in the License file.
*
----------------------------------------------------------------------------------------*/
#include "../import/head.h"
#include "../global/head.h"
#include "../macro/head.h"
#include "aio_impl.h"
#include "aio_udp.h"

/////////////////////////////////////////////////////////////////////////////////////////
// 
namespace xos_aio
{
    aio_udp::aio_udp( aio_impl * pAioImpl ) : m_pAioImpl( pAioImpl )
    {
    }

    aio_udp::~aio_udp()
    {
    }

    ////////////////////////////////////////////////////////////////////////////////////
    // 

    // 
    // m_bData[0] : true or false for result
    // 
    // m_nData[0] : cmd type
    // 
    // m_nData[1] : local port
    // m_szStr[1] : local ip
    // 
    // m_lpData[0] : UserKey
    // m_lpData[1] : AioKey
    // 
    int aio_udp::user_init( xos_box::i_msg * lpMsg )
    {
        using namespace std;
        int nRet = 0;

        xos::i_socket * lpSocket = 0;
        aio_key * lpKey = 0;
        int hSocket = -1;

        if( 0 == nRet )
        {
            lpMsg->set_int( 0, i_aio::AIO_UDP_INIT_RET );
            lpMsg->set_bool( 0, false );
            lpMsg->set_void( 1, 0 );
        }

        if( 0 == nRet )
        {
            nRet = g_pSysData->m_pContainer->xos()->create( xos::i_xos::XOS_OBJ_SOCKET, ( void ** )&lpSocket );
        }

        if( 0 == nRet )
        {
            xos::xos_u16 usPort = ( xos::xos_u16 )lpMsg->get_int( 1, 0 );
            const char * pszIp = lpMsg->get_str( 1, 0, 0, 0 );
            nRet = lpSocket->udp_init( pszIp, usPort );
        }

        if( 0 == nRet )
        {
            xos::xos_u16 usPort = 0;
            char szIp[100] = { 0 };
            nRet = lpSocket->get_socket_addr( szIp, &usPort );
            if( 0 == nRet )
            {
                lpMsg->set_str( 1, szIp );
                lpMsg->set_int( 1, usPort );
            }
        }

        if( 0 == nRet )
        {
            hSocket = ( int )lpSocket->get_socket();
            nRet = lpSocket->set_async( true );
        }

        if( 0 == nRet )
        {
            lpKey = aio_key::get_item_from_pool( true );
            lpKey->init();
            lpKey->m_enumHandleType = aio_key::H_TYPE_UDP;
            lpKey->m_eState = aio_key::KEY_STATE_RUNNING;
            lpKey->m_lpUserKey = lpMsg->get_void( 0, 0 );
            lpKey->m_pSocket = lpSocket;
            lpMsg->set_void( 1, lpKey );
        }

        if( 0 == nRet )
        {
            lpKey->m_nKqueueFlags = EVFILT_READ | EVFILT_WRITE;
            struct kevent change[2];
            EV_SET( &change[0], hSocket, EVFILT_WRITE, EV_ADD | EV_ENABLE, 0, 0, lpKey );
            EV_SET( &change[1], hSocket, EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0, lpKey );
            kevent( m_pAioImpl->m_hKqueue, change, 2, NULL, 0, NULL );
            lpMsg->set_bool( 0, true );
            lpSocket = 0;
            lpKey = 0;
        }

        m_pAioImpl->notify( lpMsg );
        lpMsg = 0;

        if( lpSocket )
        {
            lpSocket->release();
            lpSocket = 0;
        }

        if( lpKey )
        {
            lpKey->m_pSocket = 0;
            lpKey->release();
            lpKey = 0;
        }

        return nRet;
    }

    // 
    // m_bData[0] : true or false for opt result
    // 
    // m_nData[0] : cmd type
    // 
    // m_nData[2] : peer port
    // m_szStr[2] : peer ip
    // 
    // m_nData[4] : send len
    // m_lpBuf[0] : send buf
    // 
    // m_lpData[0] : UserKey
    // m_lpData[1] : AioKey
    // 
    int aio_udp::user_send( xos_box::i_msg * lpMsg )
    {
        using namespace std;
        int nRet = 0;

        aio_key * lpKey = ( aio_key * )lpMsg->get_void( 1, 0 );
        int ret = 0;

        lpMsg->set_int( 0, i_aio::AIO_UDP_SEND_RET );
        lpMsg->set_bool( 0, false );
        lpMsg->set_int( 4, 0 );

        {
            aio_data * pData = aio_data::get_item_from_pool( true );
            pData->m_pMsg = lpMsg;
            lpKey->m_pend_send_list.push_back( pData );
        }

        if( ( 0 == ret ) && ( aio_key::KEY_STATE_RUNNING == lpKey->m_eState ) )
        {
            ret = udp_send( lpKey );
        }

        if( aio_key::KEY_STATE_RUNNING != lpKey->m_eState )
        {
            lpKey->finish_request( m_pAioImpl );
        }

        return nRet;
    }

    // 
    // m_bData[0] : true or false for opt result
    // 
    // m_nData[0] : cmd type
    // 
    // m_nData[2] : peer port
    // m_szStr[2] : peer ip
    // 
    // m_nData[4] : send len
    // m_lpBuf[0] : send buf
    // 
    // m_lpData[0] : UserKey
    // m_lpData[1] : AioKey
    // 
    int aio_udp::udp_send( aio_key * lpKey )
    {
        using namespace std;
        int nRet = 0;

        xos::i_socket * lpSocket = lpKey->m_pSocket;
        xos_box::i_msg * lpMsg = 0;
        xos_box::i_buf * lpBuf = 0;
        int nResult = -1;

        if( ( 0 == nRet ) && ( aio_key::KEY_STATE_RUNNING != lpKey->m_eState ) )
        {
            nRet = 1;
        }

        if( ( 0 == nRet ) && !lpKey->m_bCanWrite )
        {
            nRet = 1;
        }

        if( 0 == nRet )
        {
            aio_data * p = 0;
            if( lpKey->m_pend_send_list.size() > 0 )
            {
				p = lpKey->m_pend_send_list.front();
                lpKey->m_pend_send_list.pop_front();
                lpMsg = p->m_pMsg;
                p->m_pMsg = 0;
                p->release();
                p = 0;
                lpBuf = lpMsg->get_buf( 0, 0 );
            }
            else
            {
                nRet = 1;
            }
        }

        if( 0 == nRet )
        {
            xos::xos_u16 usPort = ( xos::xos_u16 )lpMsg->get_int( 2, 0 );
            const char * pszIp = lpMsg->get_str( 2, 0, 0, 0 );
            const char * pszData = lpBuf->get_data( 0, 0, 0 );
            int len = lpBuf->get_len( 0 );
            int nSendLen = lpSocket->udp_send( pszData, len, pszIp, usPort );
            if( nSendLen > 0 )
            {
                if( nSendLen == len )
                {
                    lpMsg->set_bool( 0, true );
                }
                lpMsg->set_int( 4, nSendLen );
                nResult = 0;
            }
            else if( errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK )
            {
                lpKey->m_bCanWrite = false;
                nResult = 1;
                nRet = 1;
            }
            else
            {
                lpKey->m_bCanWrite = false;
                nResult = 2;
                nRet = 1;
            }
        }

        if( ( 0 == nResult ) || ( 2 == nResult ) )
        {
            m_pAioImpl->notify( lpMsg );
            lpMsg = 0;
        }

        if( lpMsg )
        {
            aio_data * p = aio_data::get_item_from_pool( true );
            p->init();
            p->m_pMsg = lpMsg;
            lpKey->m_pend_send_list.push_front( p );
            lpMsg = 0;
            p = 0;
        }

        if( 2 == nResult )
        {
            lpKey->finish_request( m_pAioImpl );
        }

        if( !lpKey->m_bCanWrite )
        {
            struct kevent change[1];
            EV_SET( &change[0], ( int )lpSocket->get_socket(), EVFILT_WRITE, EV_ENABLE, 0, 0, lpKey );
            kevent( m_pAioImpl->m_hKqueue, change, 1, NULL, 0, NULL );
        }
        else if( 0 == lpKey->m_pend_send_list.size() )
        {
            struct kevent change[1];
            EV_SET( &change[0], ( int )lpSocket->get_socket(), EVFILT_WRITE, EV_DISABLE, 0, 0, lpKey );
            kevent( m_pAioImpl->m_hKqueue, change, 1, NULL, 0, NULL );
        }

        return nRet;
    }

    // 
    // m_bData[0] : true or false for opt result
    // 
    // m_nData[0] : cmd type
    // 
    // m_nData[2] : peer port
    // m_szStr[2] : peer ip
    // 
    // m_nData[3] : recv len
    // 
    // m_lpBuf[0] : recv buf
    // 
    // m_lpData[0] : UserKey
    // m_lpData[1] : AioKey
    // 
    int aio_udp::user_recv( xos_box::i_msg * lpMsg )
    {
        using namespace std;
        int nRet = 0;

        aio_key * lpKey = ( aio_key * )lpMsg->get_void( 1, 0 );
        xos_box::i_buf * lpBuf = lpMsg->get_buf( 0, 0 );
        xos_box::i_msg * lpmsg = 0;

        lpMsg->set_int( 0, i_aio::AIO_UDP_RECV_RET );
        lpMsg->set_bool( 0, false );
        lpMsg->set_int( 3, 0 );

        if( lpKey->m_recv_list.size() > 0 )
        {
            aio_data * pD = lpKey->m_recv_list.front();
            lpKey->m_recv_list.pop_front();
            lpmsg = pD->m_pMsg;
            pD->m_pMsg = 0;
            pD->release();
            pD = 0;
        }

        if( lpmsg )
        {
            xos_box::i_buf * lpbuf = lpmsg->get_buf( 0, 0 );

            lpMsg->set_bool( 0, lpmsg->get_bool( 0, 0 ) );
            lpMsg->set_int( 0, lpmsg->get_int( 0, 0 ) );

            lpMsg->set_str( 2, lpmsg->get_str( 2, 0, 0, 0 ) );
            lpMsg->set_int( 2, lpmsg->get_int( 2, 0 ) );
            lpMsg->set_int( 3, lpmsg->get_int( 3, 0 ) );
            if( lpmsg->get_bool( 0, 0 ) )
            {
                lpBuf->set_data( lpbuf->get_data( 0, 0, 0 ), lpbuf->get_len( 0 ) );
            }
            m_pAioImpl->notify( lpMsg );

            lpMsg = 0;
            lpmsg->release();
            lpmsg = 0;
            lpbuf->release();
            lpbuf = 0;
        }
        else
        {
            aio_data * pData = aio_data::get_item_from_pool( true );
            pData->m_pMsg = lpMsg;
            lpKey->m_pend_recv_list.push_back( pData );
        }

        if( aio_key::KEY_STATE_RUNNING != lpKey->m_eState )
        {
            lpKey->finish_request( m_pAioImpl );
        }

        return nRet;
    }

    // 
    // m_bData[0] : true or false for opt result
    // 
    // m_nData[0] : cmd type
    // 
    // m_nData[2] : peer port
    // m_szStr[2] : peer ip
    // 
    // m_nData[3] : recv len
    // 
    // m_lpBuf[0] : recv buf
    // 
    // m_lpData[0] : UserKey
    // m_lpData[1] : AioKey
    // 
    int aio_udp::udp_recv( aio_key * lpKey )
    {
        using namespace std;
        int nRet = 0;

        xos::i_socket * lpSocket = lpKey->m_pSocket;
        xos_box::i_msg * lpMsg = 0;
        xos_box::i_buf * lpBuf = 0;
        bool bIsAddBuf = false;
        int nResult = -1;

        if( ( 0 == nRet ) && ( aio_key::KEY_STATE_RUNNING != lpKey->m_eState ) )
        {
            nRet = 1;
        }

        if( 0 == nRet )
        {
			if( lpKey->m_pend_recv_list.size() == 0 )
			{
                lpBuf = g_pSysData->m_pContainer->buf();
                lpMsg = g_pSysData->m_pContainer->msg();
                lpMsg->set_int( 0, i_aio::AIO_UDP_RECV_RET );
                lpMsg->set_buf( 0, lpBuf );
                lpMsg->set_bool( 0, false );
                lpMsg->set_void( 1, lpKey );
                lpMsg->set_int( 3, 0 );
                bIsAddBuf = true;
            }
            else
            {
				aio_data * pData = lpKey->m_pend_recv_list.front();
                lpKey->m_pend_recv_list.pop_front();
                lpMsg = pData->m_pMsg;
                pData->m_pMsg = 0;
                pData->release();
                pData = 0;
                lpBuf = lpMsg->get_buf( 0, 0 );
            }
        }

        if( 0 == nRet )
        {
            char * pBuf = lpBuf->get_data( 0, 0, 0 );
            int nSize = lpBuf->get_buf_size( 0 );
            char szIp[100] = { 0 };
            xos::xos_u16 usPort = 0;
            int len = lpSocket->udp_recv( pBuf, nSize, szIp, &usPort );
            if( len > 0 )
            {
                lpMsg->set_str( 2, szIp );
                lpMsg->set_int( 2, usPort );
                lpMsg->set_int( 3, len );
                lpMsg->set_bool( 0, true );
                nResult = 0;
            }
            else if( 0 == len )
            {
                nResult = 2;
                nRet = 1;
            }
            else if( errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK )
            {
                nResult = 1;
                nRet = 1;
            }
            else
            {
                lpMsg->set_int( 3, -1 );
                nResult = 2;
                nRet = 1;
            }
        }

        if( bIsAddBuf )
        {
            if( ( 0 == nResult ) || ( 2 == nResult ) )
            {
                aio_data * p = aio_data::get_item_from_pool( true );
                p->init();
                p->m_pMsg = lpMsg;
                lpKey->m_recv_list.push_back( p );
                lpMsg = 0;
                lpBuf = 0;
            }
            if( lpMsg )
            {
                lpMsg->release();
                lpMsg = 0;
            }
            if( lpBuf )
            {
                lpBuf->release();
                lpBuf = 0;
            }
        }
        else
        {
            if( ( 0 == nResult ) || ( 2 == nResult ) )
            {
                m_pAioImpl->notify( lpMsg );
                lpMsg = 0;
            }
            if( lpMsg )
            {
                aio_data * p = aio_data::get_item_from_pool( true );
                p->init();
                p->m_pMsg = lpMsg;
                lpKey->m_pend_recv_list.push_front( p );
                lpMsg = 0;
            }
        }

        if( 2 == nResult )
        {
            lpKey->finish_request( m_pAioImpl );
        }

        return nRet;
    }

    // 
    // m_nData[0] : cmd type
    // m_nData[1] : how
    // 
    // m_lpData[0] : UserKey
    // m_lpData[1] : AioKey
    // 
    int aio_udp::shut_down( xos_box::i_msg * lpMsg )
    {
        int nRet = 0;

        aio_key * lpKey = (aio_key *)lpMsg->get_void( 1, 0 );
        xos::i_socket * lpSocket = lpKey->m_pSocket;
        int how = lpMsg->get_int( 1, 0 );

        lpMsg->set_int( 0, i_aio::AIO_UDP_SHUTDOWN_RET );
        lpMsg->set_bool( 0, true );

        lpSocket->shut_down( how );
        {
            aio_data * p = aio_data::get_item_from_pool( true );
            p->init();
            p->m_pMsg = lpMsg;
            m_pAioImpl->m_return_list.push_back( p );
            lpMsg = 0;
            p = 0;
        }

        return nRet;
    }

    // 
    // m_bData[0] : true or false for opt result
    // 
    // m_nData[0] : cmd type
    // m_nData[1] : linger.l_onoff
    // m_nData[2] : linger.l_linger
    // 
    // m_lpData[0] : UserKey
    // m_lpData[1] : AioKey
    // 
    int aio_udp::close_net( xos_box::i_msg * lpMsg )
    {
        int nRet = 0;

        aio_key * lpKey = (aio_key *)lpMsg->get_void( 1, 0 );
        int onoff = lpMsg->get_int( 1, 0 );
        int linger = lpMsg->get_int( 2, 0 );
        xos::i_socket * lpSocket = lpKey->m_pSocket;

        lpMsg->set_int( 0, i_aio::AIO_UDP_CLOSE_RET );
        lpMsg->set_bool( 0, true );

        lpKey->m_eState = aio_key::KEY_STATE_CLOSING;
        lpSocket->close( onoff, linger );
        {
            aio_data * p = aio_data::get_item_from_pool( true );
            p->init();
            p->m_pMsg = lpMsg;
            m_pAioImpl->m_return_list.push_back( p );
            lpMsg = 0;
            p = 0;
        }

        return nRet;
    }

} // xos_aio
